/*
 * @Author: your name
 * @Date: 2021-12-07 14:41:47
 * @LastEditTime: 2022-02-17 17:45:08
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \web-vue\src\router\index.js
 */
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home'
import Login from '@/views/login'
import Index from '@/views/Index'
import User from '@/views/sys/User'
import Role from '@/views/sys/Role'
import Menu from '@/views/sys/Menu'
import UserCenter from '@/views/UserCenter'
import store from '../store'

import axios from "axios"

Vue.use(Router)



const routes = [
    {
      path: '/',
      name: 'Home',
      component: Home,
      children:[
        {
          path: '/index',
          name: 'Index',
          component: Index
        },
        {
          path: '/userCenter',
          name: 'UserCenter',
          component: UserCenter
        },
        // {
        //   path: '/users',
        //   name: 'SysUser',
        //   component: User
        // },
        // {
        //   path: '/roles',
        //   name: 'SysRole',
        //   component: Role
        // },
        // {
        //   path: '/menus',
        //   name: 'SysMenu',
        //   component: Menu
        // },
      ]
    },
    {
      path:'/login',
      name:'Login',
      component:Login
    }
  ]


const router = new Router({
  mode:'history',
  base:process.env.BASE_URL,
  routes
})

router.beforeEach((to,from,next)=>{

  let hasRoute = store.state.menus.hasRoute

  if(!hasRoute){
    axios.get("/sys/menu/nav",{
      headers:{
        Authorization: localStorage.getItem("token")
      }
    }).then(res=>{

      // 1. get menuList
      store.commit("setMenuList",res.data.data.nav)
  
      // 2. get 用户权限
      store.commit("setPermList",res.data.data.authoritys)
  
      console.log("authoritys")
      console.log(res.data.data)
  
      // 3. 动态绑定路由
      let newRoutes = router.options.routes
      res.data.data.nav.forEach(menu => {
        if(menu.children){
          menu.children.forEach(e=>{
  
            // 转成路由
            let route = menuToRoute(e)
  
            // 把路由添加到路由管理中
            if(route){
              newRoutes[0].children.push(route)
            }
          })
        }
      })

  
      // for(let i = 0,length = newRoutes.length;i<length; i+=1){
      //   const element = newRoutes[i]
        
      //   router.addRoute(element)
      // }
      router.addRoutes(newRoutes)
  
      hasRoute = true
      store.commit("changeRouteStatus",hasRoute)
    })

  }

  next()
})

const menuToRoute = (menu)=>{
  if(!menu.component){
    return null

  }
  let route = {
    name:menu.name,
    path:menu.path,
    meta:{
      icon:menu.icon,
      title:menu.title
    },
  }

  
  route.component = ()=>import('@/views/'+menu.component+'.vue')

  //console.log(route)
  return route
}

export default router